package com.xwj.controller.admin;

import com.xwj.data.StaticData;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by thinkjoy on 2017/7/10.
 */
@Slf4j
@RestController
@RequestMapping("/admin/")
public class LoginController {

    @RequestMapping(value = "login", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView login(ModelAndView modelAndView, HttpServletRequest request) {
        String exceptionException = (String) request.getAttribute("shiroLoginFailure");
        String error;
        if (exceptionException != null) {
            if (UnknownAccountException.class.getName().equals(exceptionException)) {
                //最终会抛给异常处理器
                error = "账号不存在";
            } else if (IncorrectCredentialsException.class.getName().equals(exceptionException)) {
                error = "用户名/密码错误";
            } else if ("randomCodeError".equals(exceptionException)) {
                error = "验证码错误";
            } else if (AuthenticationException.class.getName().equals(exceptionException)) {
                error = "认证失败";
            } else {
                error = "发生未知错误";
            }
            log.error("后台登陆错误:{} -> {}", error, exceptionException);
            request.setAttribute("error", error);
        }
        modelAndView.setViewName("admin/login");
        return modelAndView;
    }

    /**
     * 退出
     *
     * @return
     */
    @RequestMapping("/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletContext context = request.getServletContext();
        context.removeAttribute(StaticData.ADMIN_USER_LOGIN_ATTRIBUTE);
        if (SecurityUtils.getSubject().isAuthenticated()) {
            SecurityUtils.getSubject().logout();
        }
        response.sendRedirect("/admin/login");
    }

}
